<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import type { GoodsShelvesVo } from '@/types/goodsShelves'
import { getVmVolistAPI } from '@/services/goodsShelves'
import { putStorageOrPickUpAPI } from '@/services/donation'

// 设备号
const deviceNumber = 'iSknMG7O'

// 行列数
const rowCount = 5
const columnCount = 5

// 货架列表
const shelvesList = ref<GoodsShelvesVo[]>([])

// 加载状态
const loading = ref(false)

// 从左到右，从上到下排列的二维数组
const shelvesGrid = ref<(GoodsShelvesVo | null)[][]>([])

// 获取货架数据
const getShelvesList = async () => {
  if (loading.value) return

  loading.value = true
  try {
    console.log('正在获取货架数据...')
    // 确保只传递deviceNumber参数
    const res = await getVmVolistAPI({ deviceNumber })
    console.log('货架数据响应:', res)

    if (res.code === 200 && res.rows) {
      console.log('获取到货架数据，总数:', res.rows.length)
      shelvesList.value = res.rows
      // 将一维数组转换成二维网格
      arrangeShelvesInGrid()
    } else {
      console.warn('获取货架数据失败或为空:', res)
      // 尝试使用模拟数据测试
      if (import.meta.env.DEV) {
        console.log('使用模拟数据测试界面')
        createMockData()
      }
    }
  } catch (error) {
    console.error('获取货架数据失败:', error)
    uni.showToast({
      title: '获取货架数据失败',
      icon: 'none',
    })

    // 尝试使用模拟数据测试
    if (import.meta.env.DEV) {
      console.log('使用模拟数据测试界面')
      createMockData()
    }
  } finally {
    loading.value = false
  }
}

// 创建模拟数据（仅用于测试）
const createMockData = () => {
  const mockData: GoodsShelvesVo[] = []

  // 创建25个货架（5x5）
  for (let i = 0; i < 25; i++) {
    const shelfStatus = Math.random() > 0.7 ? 1 : Math.random() > 0.5 ? 0 : 2 // 30%有物, 35%停用, 35%为空

    const item: GoodsShelvesVo = {
      id: i + 1,
      shelfNumber: `A${i + 1}`,
      deviceNumber: 'iSknMG7O',
      shelfStatus,
    }

    // 如果有物品，添加捐赠物信息
    if (shelfStatus === 1) {
      item.donation = {
        id: 1000 + i,
        oddNumber: `D${1000 + i}`,
        lovehouseId: 1,
        description: `模拟物品${i + 1}`,
        images: '/static/images/停用icon-50.svg',
        categoryId: 1,
        status: 3,
      }
    }

    mockData.push(item)
  }

  shelvesList.value = mockData
  arrangeShelvesInGrid()
}

// 将货架数据排列成二维网格
const arrangeShelvesInGrid = () => {
  console.log('开始排列货架数据为二维网格')
  // 初始化二维数组
  shelvesGrid.value = Array(rowCount)
    .fill(null)
    .map(() => Array(columnCount).fill(null))

  // 填充数据
  shelvesList.value.forEach((shelf: GoodsShelvesVo, index: number) => {
    const row = Math.floor(index / columnCount)
    const col = index % columnCount
    if (row < rowCount && col < columnCount) {
      shelvesGrid.value[row][col] = shelf
    }
  })

  console.log('货架数据排列完成:', shelvesGrid.value)
}

// 处理取货按钮点击
const handlePickup = (shelf: GoodsShelvesVo) => {
  console.log('取货', shelf)
  // 这里可以实现取货逻辑，例如弹窗确认等
  uni.showModal({
    title: '取货',
    content: `确认从货架 ${shelf.shelfNumber} 取货吗？`,
    success: async (res) => {
      if (res.confirm) {
        const res = await putStorageOrPickUpAPI(shelf, 'pickup')
        if (res.code === 200) {
          uni.showToast({
            title: '已取货',
            icon: 'success',
          })
          // 刷新数据
          setTimeout(() => {
            refreshData()
          }, 1000)
        } else {
          uni.showToast({
            title: res.msg,
            icon: 'error',
          })
        }
      }
    },
  })
}

// 暴露给父组件的刷新方法
const refreshData = () => {
  console.log('开始刷新货架数据')
  getShelvesList()
}

// 暴露方法给父组件
defineExpose({
  refreshData,
})

onMounted(() => {
  console.log('device-shelf组件已挂载，准备获取数据')
  getShelvesList()
})
</script>

<template>
  <view class="device-shelf">
    <view class="shelf-container">
      <view v-if="loading" class="loading">
        <text>加载中...</text>
      </view>

      <scroll-view
        v-else-if="shelvesList.length > 0"
        scroll-x
        scroll-y
        enable-flex
        class="shelf-scroll"
        refresher-enabled
        @refresherrefresh="refreshData"
        :refresher-triggered="false"
      >
        <view class="shelf-grid">
          <view v-for="(row, rowIndex) in shelvesGrid" :key="rowIndex" class="shelf-row">
            <view
              v-for="(shelf, colIndex) in row"
              :key="`${rowIndex}-${colIndex}`"
              class="shelf-item"
            >
              <view class="shelf-content">
                <!-- 货架编号 -->
                <text class="shelf-number">{{
                  shelf?.shelfNumber || `${rowIndex + 1}-${colIndex + 1}`
                }}</text>

                <!-- 根据状态显示不同内容 -->
                <template v-if="shelf && shelf.shelfStatus === 1 && shelf.donation?.status === 3">
                  <!-- 有物品状态 -->
                  <image
                    v-if="shelf.donation.images"
                    class="shelf-image"
                    :src="shelf.donation.images.split(',')[0]"
                    mode="aspectFill"
                  />
                  <view class="pickup-btn" @tap.stop="handlePickup(shelf)">取货</view>
                </template>
                <template v-else>
                  <!-- 空或停用状态 -->
                  <image
                    class="shelf-image"
                    src="@/static/images/停用icon-50.svg"
                    mode="aspectFit"
                  />
                </template>
              </view>
            </view>
          </view>
        </view>
      </scroll-view>

      <view v-else class="empty-tip">
        <text>暂无货架数据</text>
      </view>
    </view>
  </view>
</template>

<style lang="scss">
.device-shelf {
  height: 100%;

  .loading {
    display: flex;
    justify-content: center;
    align-items: center;
    height: 300rpx;
    color: #666;
  }

  .empty-tip {
    display: flex;
    justify-content: center;
    align-items: center;
    height: 300rpx;
    color: #999;
    font-size: 28rpx;
  }

  .shelf-container {
    padding: 20rpx;
    height: calc(100vh - 200rpx);
  }

  .shelf-scroll {
    width: 100%;
    height: 100%;
  }

  .shelf-grid {
    display: flex;
    flex-direction: column;
    min-width: 100%;
    min-height: 100%;
    padding: 10rpx;
  }

  .shelf-row {
    display: flex;
    margin-bottom: 20rpx;
  }

  .shelf-item {
    flex-shrink: 0;
    width: 130rpx;
    height: 180rpx;
    margin-right: 20rpx;
    background-color: #fff;
    border-radius: 10rpx;
    box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.1);
    overflow: hidden;
  }

  .shelf-content {
    display: flex;
    flex-direction: column;
    height: 100%;
    position: relative;
  }

  .shelf-number {
    font-size: 22rpx;
    color: #666;
    background-color: rgba(255, 255, 255, 0.8);
    padding: 4rpx 8rpx;
    position: absolute;
    top: 0;
    left: 0;
    z-index: 1;
  }

  .shelf-image {
    width: 100%;
    height: 130rpx;
    object-fit: cover;
  }

  .pickup-btn {
    height: 50rpx;
    line-height: 50rpx;
    font-size: 24rpx;
    color: #fff;
    background-color: #2b85e4;
    text-align: center;
    border-radius: 0 0 10rpx 10rpx;
  }
}
</style>
